<template>
  <meta name="referrer" content="no-referrer" />
  <table class="cart">
    <caption>
      购物车
    </caption>
    <tr>
      <th>全选<input type="checkbox" v-model="selectAll" /></th>
      <th>商品</th>
      <th>单价</th>
      <th>数量</th>
      <th>小计</th>
      <th>操作</th>
    </tr>
    <tr v-for="(book, index) in books" :key="book.id">
      <td><input type="checkbox" v-model="book.isSelected" /></td>
      <td><img :src="book.productCover" />{{ book.productName }}</td>
      <td>{{ book.productPrice }}</td>
      <td>
        <input
          type="number"
          style="width: 35px"
          min="1"
          v-model="book.productCount" />
      </td>
      <td>{{ dollar(book.productPrice, book.productCount) }}</td>
      <td>
        <button @click="books.splice(index, 1)">移除</button>
      </td>
    </tr>

    <tr v-if="books.length">
      <td colspan="6">总价格: {{ total }}</td>
    </tr>
    <tr v-else>
      <td colspan="6">购物车中没有商品</td>
    </tr>
  </table>
</template>

<script setup>
import { computed } from "@vue/reactivity"
import { ref } from "vue"
console.log()
const books = ref([
  {
    isSelected: true,
    productCover:
      "https://img3.doubanio.com/view/subject/m/public/s33510542.jpg",
    productName: "纸上行舟",
    productInfo: "青年作者黎幺短篇小说首度结集",
    productPrice: 57.33,
    productCount: 3,
    id: "0001",
  },
  {
    isSelected: true,
    productCover:
      "https://img3.doubanio.com/view/subject/m/public/s33497735.jpg",
    productName: "我可能得抑郁症了！舟",
    productInfo: "青年作者黎幺短篇小说首度结集",
    productPrice: 54.26,
    productCount: 2,
    id: "0002",
  },
  {
    isSelected: true,
    productCover:
      "https://img3.doubanio.com/view/subject/m/public/s33474961.jpg",
    productName: "绕日飞行",
    productInfo: "驯马、飞行、成长、爱情",
    productPrice: 22.67,
    productCount: 3,
    id: "0003",
  },
])
//  渲染价格
const dollar = computed(() => {
  return (productPrice, productCount) => {
    // console.log(p);
    let dollar = productPrice * productCount
    return "$" + dollar.toFixed(2)
  }
})
//   总金额
const total = computed(() => {
  let total = 0
  for (let item of books.value) {
    // console.log(item);
    if (item.isSelected == true) {
      total += item.productPrice * item.productCount
    }
  }
  return "$" + total.toFixed(2)
})
// 全选
const selectAll = computed({
  get() {
    return books.value.every((item) => item.isSelected)
  },
  set(val) {
    books.value.forEach((item) => (item.isSelected = val))
  },
})
</script>

<style scoped>
table,
tr,
th,
td {
  border: 1px solid #ddd;
  border-collapse: collapse;
  border-spacing: 0;
}
img {
  width: 100px;
  height: 100px;
}
</style>
